package pers.zifeng.distributed.lock.zookeeper.event;

import lombok.extern.slf4j.Slf4j;
import pers.zifeng.distributed.lock.common.MysqlService;
import pers.zifeng.distributed.lock.zookeeper.service.ZookeeperLockService;

/**
 * @author: zf
 * @date: 2021/05/26 14:58:21
 * @version: 1.0.0
 * @description: zookeeper分布式锁自实现demo
 * 执行流程：多进程向某个永久根节点注册临时有序节点，注册成功后查看当前节点是否为首节点，是则执行业务，否则监听上一节点阻塞，等待上一节点释放再执行业务
 */
@Slf4j
public class ZookeeperBasicLock {

    public void buyMaskWithLock() throws InterruptedException {
        ZookeeperLockService zookeeperLookService = null;
        try {
            zookeeperLookService = new ZookeeperLockService();
            while (true) {
                // 创建节点
                zookeeperLookService.createLock();
                // 获取节点
                zookeeperLookService.attemptLock();
                // 业务
                if (!MysqlService.buyMask()) {
                    break;
                }
                // 删除节点
                zookeeperLookService.releaseLock();
            }
        } catch (Exception e) {
            log.error("抢购口罩失败！", e);
        } finally {
            if (zookeeperLookService != null) {
                // 关闭zookeeper连接
                zookeeperLookService.closeConnect();
            }
            // 关闭MysqlService
            MysqlService.close();
        }

    }

    public static void main(String[] args) {
        try {
            ZookeeperBasicLock basicLock = new ZookeeperBasicLock();
            basicLock.buyMaskWithLock();
        } catch (Exception e) {
            log.error("关闭zk连接失败！", e);
        }

    }

}
